using CollabApp.Application.Interfaces;
using CollabApp.Domain.Entities.Game;
using CollabApp.Domain.Services.Game;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace CollabApp.Application.Services.Game;

/// <summary>
/// 游戏状态管理服务实现
/// 负责管理游戏的整体状态，包括游戏生命周期、状态转换和状态验证
/// </summary>
public class GameStateService : IGameStateService
{
    private readonly IRedisService _redisService;
    private readonly ILogger<GameStateService> _logger;

    /// <summary>
    /// Redis键格式
    /// </summary>
    private static class RedisKeys
    {
        public const string Game = "game:{0}";
        public const string GameState = "game_state:{0}";
        public const string GamePlayers = "game_players:{0}";
        public const string GameMetrics = "game_metrics:{0}";
        public const string GameTimers = "game_timers:{0}";
        public const string StateTransitionLog = "state_transition:{0}";
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="redisService">Redis服务</param>
    /// <param name="logger">日志记录器</param>
    public GameStateService(
        IRedisService redisService,
        ILogger<GameStateService> logger)
    {
        _redisService = redisService ?? throw new ArgumentNullException(nameof(redisService));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// 初始化新游戏
    /// </summary>
    public async Task<CollabApp.Domain.Entities.Game.Game> InitializeGameAsync(
        Guid gameId, 
        Guid roomId, 
        GameSettings gameSettings)
    {
        try
        {
            _logger.LogInformation("开始初始化游戏 - GameId: {GameId}, RoomId: {RoomId}", gameId, roomId);

            // 验证参数
            ValidateInitializationParameters(gameId, roomId, gameSettings);

            // 创建游戏实例
            var game = CollabApp.Domain.Entities.Game.Game.CreateGame(
                roomId,
                gameSettings.GameMode.ToString().ToLower(),
                gameSettings.MapWidth,
                gameSettings.MapHeight,
                (int)gameSettings.Duration.TotalSeconds,
                gameSettings.MapShape);

            // 设置游戏ID
            var gameIdProperty = typeof(CollabApp.Domain.Entities.Game.Game)
                .GetProperty("Id", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            gameIdProperty?.SetValue(game, gameId);

            // 保存游戏基本信息到Redis
            await SaveGameToRedisAsync(gameId, game, gameSettings);

            // 初始化游戏状态
            await InitializeGameStateAsync(gameId, gameSettings);

            // 初始化游戏指标
            await InitializeGameMetricsAsync(gameId);

            // 设置游戏定时器
            await SetupGameTimersAsync(gameId, gameSettings);

            _logger.LogInformation("游戏初始化完成 - GameId: {GameId}", gameId);
            return game;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "初始化游戏失败 - GameId: {GameId}", gameId);
            throw;
        }
    }

    /// <summary>
    /// 开始游戏
    /// </summary>
    public async Task<bool> StartGameAsync(Guid gameId)
    {
        try
        {
            _logger.LogInformation("开始游戏 - GameId: {GameId}", gameId);

            // 获取当前游戏状态
            var currentState = await GetGameStateAsync(gameId);
            if (currentState == null)
            {
                _logger.LogWarning("游戏不存在 - GameId: {GameId}", gameId);
                return false;
            }

            // 验证状态转换
            if (!await ValidateStateTransitionAsync(gameId, GameStatus.Playing))
            {
                _logger.LogWarning("无法开始游戏，状态转换无效 - GameId: {GameId}, CurrentStatus: {Status}", 
                    gameId, currentState.Status);
                return false;
            }

            // 检查玩家数量
            var playerCount = await GetConnectedPlayerCountAsync(gameId);
            if (playerCount < 2)
            {
                _logger.LogWarning("玩家数量不足，无法开始游戏 - GameId: {GameId}, PlayerCount: {Count}", 
                    gameId, playerCount);
                return false;
            }

            // 更新游戏状态
            var startTime = DateTime.UtcNow;
            var metadata = new Dictionary<string, object>
            {
                ["start_time"] = startTime,
                ["player_count"] = playerCount,
                ["started_by"] = "system"
            };

            var success = await UpdateGameStateAsync(gameId, GameStatus.Playing, metadata);
            if (!success)
            {
                _logger.LogError("更新游戏状态失败 - GameId: {GameId}", gameId);
                return false;
            }

            // 启动游戏计时器
            await StartGameTimerAsync(gameId, startTime);

            // 记录游戏开始事件
            await LogStateTransitionAsync(gameId, GameStatus.Preparing, GameStatus.Playing, "Game started");

            _logger.LogInformation("游戏开始成功 - GameId: {GameId}, PlayerCount: {Count}", gameId, playerCount);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "开始游戏失败 - GameId: {GameId}", gameId);
            return false;
        }
    }

    /// <summary>
    /// 结束游戏
    /// </summary>
    public async Task<GameEndResult> EndGameAsync(Guid gameId, GameEndReason reason)
    {
        try
        {
            _logger.LogInformation("结束游戏 - GameId: {GameId}, Reason: {Reason}", gameId, reason);

            // 获取当前游戏状态
            var currentState = await GetGameStateAsync(gameId);
            if (currentState == null)
            {
                throw new InvalidOperationException($"游戏不存在 - GameId: {gameId}");
            }

            // 验证状态转换
            if (!await ValidateStateTransitionAsync(gameId, GameStatus.Finished))
            {
                _logger.LogWarning("无法结束游戏，状态转换无效 - GameId: {GameId}, CurrentStatus: {Status}", 
                    gameId, currentState.Status);
            }

            // 停止游戏计时器
            await StopGameTimerAsync(gameId);

            // 收集游戏结果数据
            var endResult = await CollectGameEndDataAsync(gameId, reason);

            // 更新游戏状态为已结束
            var metadata = new Dictionary<string, object>
            {
                ["end_time"] = endResult.EndTime,
                ["end_reason"] = reason.ToString(),
                ["total_players"] = endResult.PlayerResults.Count,
                ["duration"] = endResult.Statistics.TotalDuration.TotalSeconds
            };

            await UpdateGameStateAsync(gameId, GameStatus.Finished, metadata);

            // 记录状态转换
            await LogStateTransitionAsync(gameId, currentState.Status, GameStatus.Finished, 
                $"Game ended: {reason}");

            // 清理游戏资源
            await CleanupGameResourcesAsync(gameId);

            _logger.LogInformation("游戏结束完成 - GameId: {GameId}, Duration: {Duration}s", 
                gameId, endResult.Statistics.TotalDuration.TotalSeconds);

            return endResult;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "结束游戏失败 - GameId: {GameId}", gameId);
            throw;
        }
    }

    /// <summary>
    /// 获取游戏当前状态
    /// </summary>
    public async Task<GameStateInfo> GetGameStateAsync(Guid gameId)
    {
        try
        {
            var stateKey = string.Format(RedisKeys.GameState, gameId);
            var stateData = await _redisService.GetHashAllAsync(stateKey);

            if (!stateData.Any())
            {
                _logger.LogWarning("游戏状态不存在 - GameId: {GameId}", gameId);
                return null!;
            }

            var gameStateInfo = new GameStateInfo
            {
                GameId = gameId,
                Status = ParseGameStatus(stateData.GetValueOrDefault("status") ?? "Preparing"),
                ConnectedPlayers = int.Parse(stateData.GetValueOrDefault("connected_players", "0"))
            };

            // 解析时间信息
            if (stateData.TryGetValue("start_time", out var startTimeStr) && 
                DateTime.TryParse(startTimeStr, out var startTime))
            {
                gameStateInfo.StartTime = startTime;
                gameStateInfo.ElapsedTime = DateTime.UtcNow - startTime;

                // 计算剩余时间
                if (stateData.TryGetValue("duration", out var durationStr) && 
                    int.TryParse(durationStr, out var duration))
                {
                    var remaining = duration - gameStateInfo.ElapsedTime.TotalSeconds;
                    gameStateInfo.RemainingTime = remaining > 0 ? TimeSpan.FromSeconds(remaining) : TimeSpan.Zero;
                }
            }

            // 解析状态数据
            if (stateData.TryGetValue("state_data", out var stateDataStr) && !string.IsNullOrEmpty(stateDataStr))
            {
                try
                {
                    gameStateInfo.StateData = JsonSerializer.Deserialize<Dictionary<string, object>>(stateDataStr) 
                        ?? new Dictionary<string, object>();
                }
                catch (JsonException)
                {
                    gameStateInfo.StateData = new Dictionary<string, object>();
                }
            }

            return gameStateInfo;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取游戏状态失败 - GameId: {GameId}", gameId);
            return null!;
        }
    }

    /// <summary>
    /// 验证状态转换的合法性
    /// </summary>
    public async Task<bool> ValidateStateTransitionAsync(Guid gameId, GameStatus targetState)
    {
        try
        {
            var currentState = await GetGameStateAsync(gameId);
            if (currentState == null)
            {
                return false;
            }

            // 定义合法的状态转换
            var validTransitions = new Dictionary<GameStatus, GameStatus[]>
            {
                [GameStatus.Preparing] = new[] { GameStatus.Playing, GameStatus.Finished },
                [GameStatus.Playing] = new[] { GameStatus.Finished },
                [GameStatus.Finished] = new GameStatus[] { } // 结束状态不能转换到其他状态
            };

            if (!validTransitions.TryGetValue(currentState.Status, out var allowedStates))
            {
                return false;
            }

            var isValid = allowedStates.Contains(targetState);
            
            if (!isValid)
            {
                _logger.LogWarning("非法的状态转换 - GameId: {GameId}, From: {From}, To: {To}", 
                    gameId, currentState.Status, targetState);
            }

            return isValid;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "验证状态转换失败 - GameId: {GameId}", gameId);
            return false;
        }
    }

    /// <summary>
    /// 更新游戏状态
    /// </summary>
    public async Task<bool> UpdateGameStateAsync(Guid gameId, GameStatus newState, 
        Dictionary<string, object>? metadata = null)
    {
        try
        {
            var stateKey = string.Format(RedisKeys.GameState, gameId);
            var updateData = new Dictionary<string, string>
            {
                ["status"] = newState.ToString(),
                ["last_update"] = DateTime.UtcNow.ToString("O")
            };

            // 添加元数据
            if (metadata != null)
            {
                foreach (var kvp in metadata)
                {
                    updateData[kvp.Key] = kvp.Value?.ToString() ?? "";
                }
            }

            // 状态特殊处理
            if (newState == GameStatus.Playing && metadata?.ContainsKey("start_time") == true)
            {
                updateData["start_time"] = metadata["start_time"]?.ToString() ?? "";
            }
            else if (newState == GameStatus.Finished && metadata?.ContainsKey("end_time") == true)
            {
                updateData["end_time"] = metadata["end_time"]?.ToString() ?? "";
            }

            // 批量更新状态数据
            await _redisService.SetHashMultipleAsync(stateKey, updateData);

            // 设置状态过期时间（游戏结束后1小时）
            if (newState == GameStatus.Finished)
            {
                await _redisService.SetExpireAsync(stateKey, TimeSpan.FromHours(1));
            }

            _logger.LogDebug("游戏状态已更新 - GameId: {GameId}, NewState: {State}", gameId, newState);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新游戏状态失败 - GameId: {GameId}", gameId);
            return false;
        }
    }

    #region 私有辅助方法

    /// <summary>
    /// 验证初始化参数
    /// </summary>
    private static void ValidateInitializationParameters(Guid gameId, Guid roomId, GameSettings gameSettings)
    {
        if (gameId == Guid.Empty)
            throw new ArgumentException("游戏ID不能为空", nameof(gameId));
        if (roomId == Guid.Empty)
            throw new ArgumentException("房间ID不能为空", nameof(roomId));
        if (gameSettings == null)
            throw new ArgumentNullException(nameof(gameSettings));
        if (gameSettings.Duration.TotalSeconds < 30 || gameSettings.Duration.TotalSeconds > 3600)
            throw new ArgumentException("游戏时长必须在30秒到1小时之间");
        if (gameSettings.MaxPlayers < 2 || gameSettings.MaxPlayers > 10)
            throw new ArgumentException("最大玩家数必须在2-10之间");
        if (gameSettings.MapWidth <= 0 || gameSettings.MapHeight <= 0)
            throw new ArgumentException("地图尺寸必须大于0");
    }

    /// <summary>
    /// 保存游戏信息到Redis
    /// </summary>
    private async Task SaveGameToRedisAsync(Guid gameId, CollabApp.Domain.Entities.Game.Game game, GameSettings settings)
    {
        var gameKey = string.Format(RedisKeys.Game, gameId);
        var gameData = new Dictionary<string, string>
        {
            ["id"] = gameId.ToString(),
            ["room_id"] = game.RoomId.ToString(),
            ["game_mode"] = game.GameMode,
            ["map_width"] = game.MapWidth.ToString(),
            ["map_height"] = game.MapHeight.ToString(),
            ["duration"] = game.Duration.ToString(),
            ["map_shape"] = game.MapShape,
            ["powerup_spawn_interval"] = game.PowerUpSpawnInterval.ToString(),
            ["max_powerups"] = game.MaxPowerUps.ToString(),
            ["special_event_chance"] = game.SpecialEventChance.ToString(),
            ["enable_dynamic_balance"] = game.EnableDynamicBalance.ToString(),
            ["max_players"] = settings.MaxPlayers.ToString(),
            ["min_players"] = settings.MinPlayers.ToString(),
            ["created_at"] = DateTime.UtcNow.ToString("O")
        };

        await _redisService.SetHashMultipleAsync(gameKey, gameData);
        await _redisService.SetExpireAsync(gameKey, TimeSpan.FromHours(2)); // 2小时过期
    }

    /// <summary>
    /// 初始化游戏状态
    /// </summary>
    private async Task InitializeGameStateAsync(Guid gameId, GameSettings settings)
    {
        var stateKey = string.Format(RedisKeys.GameState, gameId);
        var stateData = new Dictionary<string, string>
        {
            ["status"] = GameStatus.Preparing.ToString(),
            ["connected_players"] = "0",
            ["duration"] = ((int)settings.Duration.TotalSeconds).ToString(),
            ["max_players"] = settings.MaxPlayers.ToString(),
            ["created_at"] = DateTime.UtcNow.ToString("O"),
            ["last_update"] = DateTime.UtcNow.ToString("O")
        };

        await _redisService.SetHashMultipleAsync(stateKey, stateData);
    }

    /// <summary>
    /// 初始化游戏指标
    /// </summary>
    private async Task InitializeGameMetricsAsync(Guid gameId)
    {
        var metricsKey = string.Format(RedisKeys.GameMetrics, gameId);
        var metricsData = new Dictionary<string, string>
        {
            ["total_actions"] = "0",
            ["total_collisions"] = "0",
            ["total_powerups_collected"] = "0",
            ["total_territory_captured"] = "0",
            ["peak_player_count"] = "0",
            ["start_time"] = "",
            ["end_time"] = ""
        };

        await _redisService.SetHashMultipleAsync(metricsKey, metricsData);
    }

    /// <summary>
    /// 设置游戏定时器
    /// </summary>
    private async Task SetupGameTimersAsync(Guid gameId, GameSettings settings)
    {
        var timersKey = string.Format(RedisKeys.GameTimers, gameId);
        var timersData = new Dictionary<string, string>
        {
            ["duration"] = ((int)settings.Duration.TotalSeconds).ToString(),
            ["powerup_spawn_interval"] = settings.PowerUpSpawnInterval.ToString(),
            ["next_powerup_spawn"] = "0",
            ["shrinking_phase_start"] = "30", // 最后30秒开始缩圈
            ["created_at"] = DateTime.UtcNow.ToString("O")
        };

        await _redisService.SetHashMultipleAsync(timersKey, timersData);
    }

    /// <summary>
    /// 获取已连接玩家数量
    /// </summary>
    private async Task<int> GetConnectedPlayerCountAsync(Guid gameId)
    {
        var playersKey = string.Format(RedisKeys.GamePlayers, gameId);
        var playerCount = await _redisService.GetSetCardinalityAsync(playersKey);
        return (int)playerCount;
    }

    /// <summary>
    /// 启动游戏计时器
    /// </summary>
    private async Task StartGameTimerAsync(Guid gameId, DateTime startTime)
    {
        var timersKey = string.Format(RedisKeys.GameTimers, gameId);
        var timerUpdates = new Dictionary<string, string>
        {
            ["game_start_time"] = startTime.ToString("O"),
            ["next_powerup_spawn"] = DateTime.UtcNow.AddSeconds(25).ToString("O") // 25秒后第一个道具
        };

        await _redisService.SetHashMultipleAsync(timersKey, timerUpdates);
    }

    /// <summary>
    /// 停止游戏计时器
    /// </summary>
    private async Task StopGameTimerAsync(Guid gameId)
    {
        var timersKey = string.Format(RedisKeys.GameTimers, gameId);
        await _redisService.SetHashAsync(timersKey, "game_end_time", DateTime.UtcNow.ToString("O"));
    }

    /// <summary>
    /// 收集游戏结束数据
    /// </summary>
    private async Task<GameEndResult> CollectGameEndDataAsync(Guid gameId, GameEndReason reason)
    {
        var endTime = DateTime.UtcNow;
        var result = new GameEndResult
        {
            GameId = gameId,
            Reason = reason,
            EndTime = endTime
        };

        // 获取游戏统计信息
        var statistics = await CollectGameStatisticsAsync(gameId, endTime);
        result.Statistics = statistics;

        // 获取玩家结果
        var playerResults = await CollectPlayerResultsAsync(gameId);
        result.PlayerResults = playerResults;

        return result;
    }

    /// <summary>
    /// 收集游戏统计信息
    /// </summary>
    private async Task<GameStatistics> CollectGameStatisticsAsync(Guid gameId, DateTime endTime)
    {
        var statistics = new GameStatistics();

        try
        {
            // 从游戏指标中获取统计数据
            var metricsKey = string.Format(RedisKeys.GameMetrics, gameId);
            var metricsData = await _redisService.GetHashAllAsync(metricsKey);

            if (metricsData.Any())
            {
                statistics.TotalActions = int.Parse(metricsData.GetValueOrDefault("total_actions", "0"));
                
                // 计算游戏总时长
                if (metricsData.TryGetValue("start_time", out var startTimeStr) && 
                    DateTime.TryParse(startTimeStr, out var startTime))
                {
                    statistics.TotalDuration = endTime - startTime;
                }

                // 设置动作计数
                statistics.ActionCounts = new Dictionary<string, int>
                {
                    ["collisions"] = int.Parse(metricsData.GetValueOrDefault("total_collisions", "0")),
                    ["powerups_collected"] = int.Parse(metricsData.GetValueOrDefault("total_powerups_collected", "0")),
                    ["territory_captured"] = int.Parse(metricsData.GetValueOrDefault("total_territory_captured", "0"))
                };
            }

            // 获取玩家总数
            var playersKey = string.Format(RedisKeys.GamePlayers, gameId);
            statistics.TotalPlayers = (int)await _redisService.GetSetCardinalityAsync(playersKey);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "收集游戏统计信息失败 - GameId: {GameId}", gameId);
        }

        return statistics;
    }

    /// <summary>
    /// 收集玩家结果
    /// </summary>
    private async Task<List<PlayerGameResult>> CollectPlayerResultsAsync(Guid gameId)
    {
        var results = new List<PlayerGameResult>();

        try
        {
            var playersKey = string.Format(RedisKeys.GamePlayers, gameId);
            var playerIds = await _redisService.GetSetMembersAsync(playersKey);

            foreach (var playerIdStr in playerIds)
            {
                if (Guid.TryParse(playerIdStr, out var playerId))
                {
                    // 这里需要从其他服务获取玩家详细结果
                    // 目前创建基础结果
                    var result = new PlayerGameResult
                    {
                        PlayerId = playerId,
                        PlayerName = $"Player_{playerId.ToString()[..8]}", // 临时名称
                        Score = 0,
                        Rank = 0,
                        PlayTime = TimeSpan.Zero,
                        Statistics = new Dictionary<string, object>()
                    };

                    results.Add(result);
                }
            }

            // 简单排序（需要根据实际评分逻辑调整）
            for (int i = 0; i < results.Count; i++)
            {
                results[i].Rank = i + 1;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "收集玩家结果失败 - GameId: {GameId}", gameId);
        }

        return results;
    }

    /// <summary>
    /// 清理游戏资源
    /// </summary>
    private async Task CleanupGameResourcesAsync(Guid gameId)
    {
        try
        {
            // 设置所有游戏相关键的过期时间
            var keys = new[]
            {
                string.Format(RedisKeys.GamePlayers, gameId),
                string.Format(RedisKeys.GameTimers, gameId),
                string.Format(RedisKeys.GameMetrics, gameId)
            };

            var tasks = keys.Select(key => _redisService.SetExpireAsync(key, TimeSpan.FromHours(1)));
            await Task.WhenAll(tasks);

            _logger.LogDebug("游戏资源清理完成 - GameId: {GameId}", gameId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "清理游戏资源失败 - GameId: {GameId}", gameId);
        }
    }

    /// <summary>
    /// 记录状态转换日志
    /// </summary>
    private async Task LogStateTransitionAsync(Guid gameId, GameStatus fromState, GameStatus toState, string reason)
    {
        try
        {
            var logKey = string.Format(RedisKeys.StateTransitionLog, gameId);
            var logEntry = JsonSerializer.Serialize(new
            {
                from_state = fromState.ToString(),
                to_state = toState.ToString(),
                reason = reason,
                timestamp = DateTime.UtcNow.ToString("O"),
                game_id = gameId.ToString()
            });

            await _redisService.ListPushAsync(logKey, logEntry);
            await _redisService.SetExpireAsync(logKey, TimeSpan.FromHours(2));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "记录状态转换日志失败 - GameId: {GameId}", gameId);
        }
    }

    /// <summary>
    /// 解析游戏状态
    /// </summary>
    private static GameStatus ParseGameStatus(string statusStr)
    {
        return Enum.TryParse<GameStatus>(statusStr, true, out var status) ? status : GameStatus.Preparing;
    }

    /// <summary>
    /// 创建团队游戏
    /// </summary>
    public async Task<CreateGameResult> CreateTeamGameAsync(Guid roomId, int teamCount, int playersPerTeam, GameSettings gameSettings)
    {
        try
        {
            var gameId = Guid.NewGuid();
            gameSettings.GameMode = GameMode.Team;
            gameSettings.CustomSettings["teamCount"] = teamCount;
            gameSettings.CustomSettings["playersPerTeam"] = playersPerTeam;

            var game = await InitializeGameAsync(gameId, roomId, gameSettings);

            _logger.LogInformation("创建团队游戏成功: {GameId}, 队伍数: {TeamCount}, 每队人数: {PlayersPerTeam}", 
                gameId, teamCount, playersPerTeam);

            return new CreateGameResult
            {
                Success = true,
                GameId = gameId,
                Message = "团队游戏创建成功",
                GameData = new Dictionary<string, object>
                {
                    ["teamCount"] = teamCount,
                    ["playersPerTeam"] = playersPerTeam,
                    ["gameMode"] = "Team"
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建团队游戏失败: {Message}", ex.Message);
            return new CreateGameResult
            {
                Success = false,
                Message = "创建团队游戏失败",
                Errors = new List<string> { ex.Message }
            };
        }
    }

    /// <summary>
    /// 创建生存游戏
    /// </summary>
    public async Task<CreateGameResult> CreateSurvivalGameAsync(Guid roomId, GameSettings gameSettings)
    {
        try
        {
            var gameId = Guid.NewGuid();
            gameSettings.GameMode = GameMode.Survival;
            gameSettings.CustomSettings["enableRespawn"] = false;
            gameSettings.CustomSettings["oneLife"] = true;

            var game = await InitializeGameAsync(gameId, roomId, gameSettings);

            _logger.LogInformation("创建生存游戏成功: {GameId}", gameId);

            return new CreateGameResult
            {
                Success = true,
                GameId = gameId,
                Message = "生存游戏创建成功",
                GameData = new Dictionary<string, object>
                {
                    ["gameMode"] = "Survival",
                    ["oneLife"] = true
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建生存游戏失败: {Message}", ex.Message);
            return new CreateGameResult
            {
                Success = false,
                Message = "创建生存游戏失败",
                Errors = new List<string> { ex.Message }
            };
        }
    }

    /// <summary>
    /// 创建极速游戏
    /// </summary>
    public async Task<CreateGameResult> CreateSpeedGameAsync(Guid roomId, float speedMultiplier, GameSettings gameSettings)
    {
        try
        {
            var gameId = Guid.NewGuid();
            gameSettings.GameMode = GameMode.Speed;
            gameSettings.Duration = TimeSpan.FromSeconds(90); // 极速模式固定90秒
            gameSettings.CustomSettings["speedMultiplier"] = speedMultiplier;

            var game = await InitializeGameAsync(gameId, roomId, gameSettings);

            _logger.LogInformation("创建极速游戏成功: {GameId}, 速度倍数: {SpeedMultiplier}", 
                gameId, speedMultiplier);

            return new CreateGameResult
            {
                Success = true,
                GameId = gameId,
                Message = "极速游戏创建成功",
                GameData = new Dictionary<string, object>
                {
                    ["gameMode"] = "Speed",
                    ["speedMultiplier"] = speedMultiplier,
                    ["duration"] = 90
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建极速游戏失败: {Message}", ex.Message);
            return new CreateGameResult
            {
                Success = false,
                Message = "创建极速游戏失败",
                Errors = new List<string> { ex.Message }
            };
        }
    }

    #endregion
}
